// Learn cc.Class:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/class.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/class.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/en/scripting/life-cycle-callbacks.html

cc.Class({
    extends: cc.Component,

    properties: {
        //障碍物实例对象
        ObstaclePrefab:{
            default:[],
            type:cc.Prefab,
        },

        //障碍物文件夹
        ObstacleFolder:{
            default: null,
            type: cc.Node
        },

        //小球的文件夹
        BallFolder:{
            default:null,
            type:cc.Node
        },

        //球的预制对象
        BallPrefab:{
            default:null,
            type:cc.Prefab
        },

        ballNum:{
            default:null,
            type:cc.Label
        },


        //障碍物数组
        ObstacleArry:[],

        //球的数组
        BallArry:{
            default:[],
            type:cc.Node
        },

        jiantou:{
            default:null,
            type:cc.Node
        },

        fenshu:{
            default:null,
            type:cc.Label
        },

        //颜色的文件夹
        ColorPreffab:[],

    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        let wuli = cc.director.getPhysicsManager();
        wuli.enabled = true;    //开启物理世界开关
        wuli.gravity = cc.v2(0,-1000);         //设置物理重力

        this.GameInit();
    },


    start () {
        this.ColorPreffab.push(cc.color(239,206,232));
        this.ColorPreffab.push(cc.color(243,215,181));
        this.ColorPreffab.push(cc.color(253,255,223));
        this.ColorPreffab.push(cc.color(218,249,202));
        this.ColorPreffab.push(cc.color(199,179,229));
        this.AddObstacle();

        //初始化一个小球
        this.BallInit(this.BallArry[0]);
    },


    update (dt) {

        if (Pellet) {
            this.AddBall(Pellet);
        }

        //把数组中球的个数，传递给全局变量
        BallArray = this.BallArry.length;

        this.BallRecoveryCompletion(); //

        let Obstacle = require("Obstacle");
        this.fenshu.string =  Obstacle.Rows();
    },


    /**
     * 游戏初始化函数
     * @constructor
     */
    GameInit() {
        //监听触摸时间知道发射点
        this.node.on('touchend', function (event) {
            this.jiantou.opacity = 0;
            if (!is_launch) {
                return null;
            }
            is_launch = false;

            let toucPosi = this.node.convertTouchToNodeSpaceAR(event.touch);

            let i = 0;
            this.schedule(function () {
                this.BallLaunch(this.BallArry[i], toucPosi);
                i++;
                BallBackHome = 0;
            }, 0.5, this.BallArry.length - 1, 0);
            is_up = true;
        }, this);


        //点击屏幕时
        this.node.on('touchstart', function (event) {
            this.jiantou.opacity = 255;
        },this);



        //添加瞄准线
        this.node.on('touchmove', function (event) {
            let toucPosi = this.node.convertTouchToNodeSpaceAR(event.touch);
            let fangxiang = toucPosi.signAngle(cc.v2(1,-409));
            this.jiantou.rotation = (180 / Math.PI) * fangxiang ;
        }, this);

    },


    /**
     * 小球发射
     * @param ball
     * @param dir
     * @constructor
     */
    BallLaunch(ball,dir){
        this.BallInit(ball);
        ball = ball._components[3];
        let ballPosi = [];
        ballPosi.push(ball.node.position);
        ballPosi.push(cc.v2(1,409));


        ball.node.runAction(cc.sequence(
            cc.cardinalSplineTo(0.2,ballPosi,0.5),
            cc.callFunc(function () {
                ball.RigidBody.active = true;
                ball.RigidBody.linearVelocity = dir.subSelf(cc.v2(1,409)).mul(3);
            })
        ));
    },



    /**
     * 随机生成一排障碍物
     * @constructor
     */
    AddObstacle(){
        RowArry++;
        let strPosiX = -258;    //生成障碍物的最左坐标
        let endPosiX = 253;     //生成障碍物的最右坐标

        let generatePosiX = strPosiX + this.getRandom() - 90;    //生成障碍物的当前坐标。

        while (generatePosiX <= endPosiX){
            let baller = cc.instantiate(this.ObstaclePrefab[Math.floor(Math.random()*this.ObstaclePrefab.length)]);
            this.ObstacleFolder.addChild(baller);
            // baller.node.parentNode = this.node;
            baller.rotation = Math.random() * 360;
            baller.color = this.ColorPreffab[Math.floor(Math.random()*this.ColorPreffab.length)];
            baller.setPosition(cc.v2(generatePosiX,-400));
            generatePosiX += this.getRandom();
            this.ObstacleArry.push(baller);
        }
    },


    /**
     * 生成一个小球
     * @param dir
     * @constructor
     */
    AddBall(dir){
        Pellet = false;
        cc.log('生成一个小球');
        let ball = cc.instantiate(this.BallPrefab);
        this.BallFolder.addChild(ball);
        ball.setPosition(dir);
        this.BallArry.push(ball);
        this.ballNum.string = this.BallArry.length;
    },


    /**
     * 为生成的障碍物生成随机坐标
     * @returns {number}
     */
    getRandom(){
        return 90 + Math.random() * 80;
    },


    /**
     * 初始化小球的位置
     * @constructor
     */
    BallInit(ball){
        ball._components[3].RigidBody.active = false;
        ball.runAction(cc.moveTo(0.5,cc.v2(1,409)));
    },


    /**
     * 验证小球是否回收完成.是否上移障碍物，和生成新的障碍物
     * @returns {boolean}
     * @constructor
     */
    BallRecoveryCompletion(){
        if(is_up && is_launch){
            this.BallInit(this.BallArry[0]);
            is_up = false;
            this.AllBallMoveUp();
        }
    },



    /**
     * 1.在数组中删除没有了的元素
     * 2.所有障碍物上移
     * @constructor
     */
    AllBallMoveUp(){
        for (let i = this.ObstacleArry.length -1; i>=0; i--){
            if (!this.ObstacleArry[i].name){
                this.ObstacleArry.splice(i,1);
            }
        }

        for(let x in this.ObstacleArry){
            let obstale = this.ObstacleArry[x];
            obstale.runAction(cc.moveBy(0.8,cc.v2(0,100)));  //
        }

        //调用生成障碍物函数
        this.scheduleOnce(function() {
            this.AddObstacle();
        }, 1);

    },


});



//是否生成小球
let Pellet = false;

//回收小数的个数
let BallBackHome = 0;

//当前数组中的小球个数
let BallArray = 0;

//障碍物是否上移
let is_up = false;

//是否能发射小球
let is_launch = true;

 //障碍物的排数
let RowArry = 0;


/**
 * 控制是否生成小球的标志位
 * @param dir
 */
module.exports.livingBall = function (dir) {
    Pellet = dir;
};

//小球返回+1 函数
module.exports.Smallone = function (ball) {
    // ball.scheduleOnce(function() {
    //     ball.group = "upBall";
    //     cc.log(ball.group)
    // }, 0.5);

    BallBackHome++;

    if (BallBackHome == BallArray){
        BallBackHome = 0;
        is_up = true;
        is_launch = true;
    }
};

//返回障碍物的个数
module.exports.Rows = function () {
    return RowArry;
};





